package modules.lobby
{
	import flash.events.MouseEvent;
	
	import fla.ui.LobbyUI;
	
	import modules.GameEvent;
	import modules.ViewManager;
	import modules.communication.CommunicationEvent;
	import modules.login.Login;

	public class LobbyViewManager extends ViewManager
	{
		private var lobbyUI:LobbyUI;

		public function LobbyViewManager()
		{
			dispatcher.addEventListener(CommunicationEvent.DISCONNECT_ACK, onGameEvent);

			dispatcher.addEventListener(CommunicationEvent.LOGIN_ACK, onGameEvent);
			dispatcher.addEventListener(CommunicationEvent.LOGOUT_ACK, onGameEvent);
		}

		private function get logined():Boolean
		{
			return Login.logined;
		}

		protected function onGameEvent(event:GameEvent):void
		{
			switch (event.type)
			{
				case CommunicationEvent.DISCONNECT_ACK:
					logined ? show() : close();
					break;
				case CommunicationEvent.LOGIN_ACK:
					logined ? show() : close();
					break;
				case CommunicationEvent.LOGOUT_ACK:
					logined ? show() : close();
					break;
			}
		}

		override public function init():void
		{
			lobbyUI = new LobbyUI();

			lobbyUI.x = (UIAllRefer.stage.stageWidth - lobbyUI.width) / 2;
			lobbyUI.y = (UIAllRefer.stage.stageHeight - lobbyUI.height) / 2;

			show();
		}

		override public function show():void
		{
			if (lobbyUI == null)
			{
				init();
				return;
			}

			addListeners();

			updateView();

			UIAllRefer.contentLayer.addChild(lobbyUI);
		}

		override public function updateView():void
		{
			lobbyUI.usernameTxt.text = GlobalData.userInfo.username;
		}

		override public function close():void
		{
			removeListeners();

			lobbyUI && lobbyUI.parent && lobbyUI.parent.removeChild(lobbyUI);
		}

		override public function addListeners():void
		{
			lobbyUI.logoutBtn.addEventListener(MouseEvent.CLICK, onClick);
			lobbyUI.createRoomBtn.addEventListener(MouseEvent.CLICK, onClick);
		}

		protected function onClick(event:MouseEvent):void
		{
			switch (event.currentTarget)
			{
				case lobbyUI.logoutBtn:
					dispatcher.dispatchEvent(new CommunicationEvent(CommunicationEvent.LOGOUT_REQ));
					break;
				case lobbyUI.createRoomBtn:
					dispatcher.dispatchEvent(new CommunicationEvent(CommunicationEvent.CREATEROOM_REQ));
					break;
			}
		}
	}
}
